<?php 
namespace Emos\Field;

use Emos\Common;

class Integer extends AbstractControl {
    protected $min = null;
    protected $max = null;
    protected $outOfRangeMessage = null;
    protected $regexp = '/^ -? \d+ $/x';
    protected $regexpMessage = 'not an integer';    
    
    public function html() {
        return "<input type='text' name='{$this->htmlName}' value='".Common::plain($this->value)."' style='width:100px' />";
    }
    
    protected function getPost() {
        return trim(parent::getPost());
    }

    public function validate() {            
        $post = $this->getPost();
        
        if(!preg_match($this->regexp, $this->getPost())) {            
            $this->error = Common::t($this->regexpMessage);            
            return false;
        }
        else {
            if(($this->min !== null) && ($this->max !== null)) {
                if(!(($this->min <= $post) && ($post <= $this->max))) {
                    $this->error = Common::t("out of range", array('min'=>$this->min, 'max'=>$this->max));            
                    return false;                
                }
            }
            return true;
        }
    }
    
    public function setRange($min=0, $max=PHP_INT_MAX, $outOfRangeMessage = null) {
        $this->min = $min;
        $this->max = $max;       
        
        if($outOfRangeMessage === null) {
           $outOfRangeMessage = Common::t("incorrect value"); 
        }        
        
        return $this;
    }
    
    public function getDdlFields() {
        return array(
            $this->dbName => "INT"
        );
    }   

    public function getFake() {
        return array(
            $this->dbName => rand(0, 1000)
        );
    }     
}